﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;

using LiBLaB.Networking.Asynchronous;
using LiBLaB.GUI;
using LiBLaB.Audio;

namespace AsyncServer
{
    public partial class ServerMainFrm : Form
    {
        Server Server;
        GUI gui;
        List<MP3> mp3Files = new List<MP3>();
        public ServerMainFrm()
        {
            InitializeComponent();
        }

        void serverAcceptConn(int client_index,bool status)
        {
            if(status)
                gui.AddToGUI(this, listBox1, "New Client Accepted, ID: " + client_index.ToString()+".");
            else
                gui.AddToGUI(this, listBox1, "Client ID: " + client_index.ToString()+ ", connection closed.");
        }

        void dataReceived(byte[] buffer,int client_index)
        {
            string message = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
            if (message == "#received#")
            {
                //mp3Files[client_index].
                byte[] data = mp3Files[client_index].NextFrame;
                if (data.Length != 0)
                    Server.Send(data, client_index);
                else
                {
                    data = Encoding.ASCII.GetBytes("End of MP3 File.");
                    Server.Send(data, client_index);
                }
            }
            else if (File.Exists(message))
            {
                gui.AddToGUI(this, listBox1, "Client ID: " + client_index.ToString() + ", ask for: " + message);
                mp3Files.Add(new MP3(message));
                //mp3Files[client_index].Seek(95);
                byte[] data = mp3Files[client_index].NextFrame;
                Server.Send(data, client_index);
            }
            else
            {
                gui.AddToGUI(this, listBox1, "Client ID: " + client_index.ToString() + ", ask for: " + message);
                byte[] data = Encoding.ASCII.GetBytes("MP3 File not found");
                Server.Send(data, client_index);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("Server started...");
            Server = new Server(9050, serverAcceptConn, dataReceived);
            gui = new GUI();
        }

        private void ServerMainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            for (int i = 0; i < mp3Files.Count; i++)
            {
                mp3Files[i].Dispose();
            }
        }
    }
}
